<template>
    <div>
        <!-- 用户信息框 -->
        <el-descriptions title="用户信息" direction="vertical" :column="4" border>
            <el-descriptions-item label="用户名">{{user.username}}</el-descriptions-item>
            <el-descriptions-item label="昵称">{{user.name}}</el-descriptions-item>
            <el-descriptions-item label="性别">{{user.gender}}</el-descriptions-item>
            <el-descriptions-item label="工作">{{user.job}}</el-descriptions-item>
            <el-descriptions-item label="地址">{{user.address}}</el-descriptions-item>
            <el-descriptions-item label="关注数">{{user.followCount}}</el-descriptions-item>
            <el-descriptions-item label="被关注数">{{user.beFollowedCount}}</el-descriptions-item>
        </el-descriptions>
        <el-button type="primary" @click="follow" v-if="canFollow&&!isFollowed">关注用户</el-button>
        <el-button type="danger" @click="cancelFollow" v-if="canFollow&&isFollowed" plain>取消关注</el-button>

        <!--登录表单-->
        <el-dialog
                title="登录账号"
                :visible.sync="loginVisible"
                width="30%"
        >
            <el-form :model="loginUser" status-icon ref="loginUser" label-width="100px" class="demo-loginUser">
                <el-form-item label="账号" prop="username">
                    <el-input v-model="loginUser.username" placeholder="请输入您的账号"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="loginUser.password" autocomplete="off" placeholder="请输入您的密码"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="login">登录</el-button>
                    <el-button @click="resetForm('loginUser')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios';
export default{
    mounted(){
        this.getInfo();
    },
    methods:{
        //获取用户信息
        async getInfo(){
            const isValidJwt = await this.checkJwt();
            let jwt='';
            if(localStorage.getItem('token')===null){
                jwt='';
            }else if(isValidJwt){
                jwt=localStorage.getItem('token');
                const parts = localStorage.getItem('token').split('.');
                if(parts.length>2){
                    const payload = parts[1];
                    const decoded = atob(payload);
                    this.loginUser.id=JSON.parse(decoded).id;
                }
            }else{
                jwt='';
                localStorage.removeItem('token')
            }
            axios({
                method:'get',
                url:'http://localhost:8080/user/'+this.$route.params.authorId,
                headers:{token:jwt}
            }).then(resp => {
                this.user=resp.data.data;
                if(jwt!==null){
                    if(this.loginUser.id===resp.data.data.id){
                        this.canFollow=false;
                    }else{
                        this.canFollow=true;
                    }
                }
                if(resp.data.data.isFollowed){
                    this.isFollowed=true;
                }else{
                    this.isFollowed=false;
                }
            })
        },

        // 检查jwt
        async checkJwt(){
            try {  
                const response = await axios({  
                    method: 'get',  
                    url: 'http://localhost:8080/check/' + localStorage.getItem('token')  
                });  
                return response.data.code;
            } catch (error) {  
                return false; 
            }
        },

        // 登录方法
        login() {
            axios({
                method:"post",
                url:"http://localhost:8080/login",
                data:this.loginUser
            }).then(resp =>{
                // 判断是否存在
                if(resp.data.code){
                    this.resetForm('loginUser');
                    this.loginVisible = false;
                    localStorage.setItem('token',resp.data.data)
                    this.$message.success("登录成功!");
                    this.getInfo();
                }else{
                    this.$message.error(resp.data.msg);
                    this.resetForm('loginUser');
                    this.loginVisible = false;
                }
            })
        },

        // 关注用户
        async follow(){
            const isValidJwt = await this.checkJwt();
            if(localStorage.getItem('token')===null){
                this.$message.error('请先登录');
                this.loginVisible=true;
            }else if(isValidJwt){
                axios({
                    method:"post",
                    url:"http://localhost:8080/follow/"+this.$route.params.authorId,
                    headers:{token:localStorage.getItem('token')}
                }).then(resp => {
                    if(resp.data.code){
                        this.getInfo();
                        this.$message.success("关注成功！")
                    }else{
                        this.$message.error(resp.data.msg)
                    }
                })
            }else{
                localStorage.removeItem('token');
                this.$message.error('请先登录');
                this.loginVisible=true;
            }
        },
        
        // 关注用户
        async cancelFollow(){
            const isValidJwt = await this.checkJwt();
            if(localStorage.getItem('token')===null){
                this.$message.error('请先登录');
                this.loginVisible=true;
            }else if(isValidJwt){
                axios({
                    method:"delete",
                    url:"http://localhost:8080/follow/"+this.$route.params.authorId,
                    headers:{token:localStorage.getItem('token')}
                }).then(resp => {
                    if(resp.data.code){
                        this.getInfo();
                        this.$message.success("取消关注成功！")
                    }else{
                        this.$message.error(resp.data.msg)
                    }
                })
            }else{
                localStorage.removeItem('token');
                this.$message.error('请先登录');
                this.loginVisible=true;
            }
        },

        // 重置方法
        resetForm(formName) {
                this.$refs[formName].resetFields();
        },
    },
    data(){
        return{
            //用户可关注标识（本人不可关注本人）
            canFollow:false,
            //用户已被关注
            isFollowed:false,
            //登录窗口是否展示标识
            loginVisible:false,
            //用户模型
            user: {
                username:'',
                name:'',
                gender:'',
                job:'',
                address:'',
                followCount:'',
                beFollowedCount:''
            },
            loginUser:{
                id:'',
                username:'',
                password:''
            }
        }
    }
}
</script>